package com.lq.fastnews.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.lq.fastnews.MyApp;
import com.lq.fastnews.R;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.io.File;


/**
 * Created by zhaokaiqiang on 15/11/7.
 */
public class ImageLoadProxy {

//    private static final int MAX_DISK_CACHE = 1024 * 1024 * 50;
//    private static final int MAX_MEMORY_CACHE = 1024 * 1024 * 10;
//
//    private static boolean isShowLog = false;

    private static ImageLoader imageLoader;
//
    public static ImageLoader getImageLoader() {

        if (imageLoader == null) {
            synchronized (ImageLoadProxy.class) {
                imageLoader = ImageLoader.getInstance();
            }
        }

        return imageLoader;
    }

    public static void initImageLoader(Context context) {

        File picPath = new File(CacheUtil.getSaveDirPath());


        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);// default 设置当前线程的优先级
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());// default为使用HASHCODE对UIL进行加密命名， 还可以用MD5(new Md5FileNameGenerator())加密
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
//        config.diskCacheFileCount(300) ; // 可以缓存的文件数量
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.memoryCacheExtraOptions(480, 800); // default = device screen dimensions 内存缓存文件的最大长宽
//        config.diskCache(new LimitedAgeDiskCache(picPath, 30 * 24 * 60 * 60 * 1000));//不限制缓存大小，但是设置缓存时间，到期后删除
        config.diskCache(new UnlimitedDiskCache(picPath));
        config.threadPoolSize(3);//线程池内加载的数量
//        config.memoryCache(new LruMemoryCache((int) (Runtime.getRuntime().totalMemory()/8))); //可以通过自己的内存缓存实现
        config.memoryCacheSize((int) (Runtime.getRuntime().maxMemory()/8));  // 内存缓存的最大值

//        config.memoryCacheSizePercentage(13); // default
//
//        config.imageDownloader(new BaseImageDownloader(getApplicationContext())); // default
//                config.defaultDisplayImageOptions(DisplayImageOptions.createSimple()); // default

        config.imageDownloader(new BaseImageDownloader(context, 5 * 1000, 30 * 1000)); // connectTimeout (5 s), readTimeout (30 s)超时时间
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }

    /**
     * 自定义Option
     *
     * @param url
     * @param target
     */
    public static void displayImage(String url, ImageView target) {
//        boolean b = MySP.isMobileLoadImage();
//        if(b&&!(NetWorkUtil.getAPNType()==NetWorkUtil.wifi)){
//            return;
//        }
        if(TextUtils.isEmpty(url)){
            return;
        }
        getImageLoader().displayImage(url + "", target, getOptions4List());

    }


    /**
     * 自定义Option
     *
     * @param url
     * @param target
     * @param options
     */
    public static void displayImage(String url, ImageView target, DisplayImageOptions options) {
        getImageLoader().displayImage(url, target, options);
    }

    /**
     * 头像专用
     *
     * @param url
     * @param target
     */
    public static void displayHeadIcon(String url, ImageView target) {

        if(TextUtils.isEmpty(url)){
            return;
        }
        getImageLoader().displayImage(url, target, getOptions4Header());
    }

    /**
     * 图片详情页专用
     *
     * @param url
     * @param target
     * @param loadingListener
     */
    public static void displayImage4Detail(String url, ImageView target, SimpleImageLoadingListener loadingListener) {
        ImageLoader.getInstance().displayImage(url, target, getOption4ExactlyType(), loadingListener);
    }

    /**
     * 图片列表页专用
     *
     * @param url
     * @param target
     * @param loadingResource
     * @param loadingListener
     * @param progressListener
     */
    public static void displayImageList(String url, ImageView target, int loadingResource, SimpleImageLoadingListener loadingListener, ImageLoadingProgressListener progressListener) {
        ImageLoader.getInstance().displayImage(url, target, getOptions4PictureList(loadingResource), loadingListener, progressListener);
    }

    /**
     * 自定义加载中图片
     *
     * @param url
     * @param target
     * @param loadingResource
     */
    public static void displayImageWithLoadingPicture(String url, ImageView target, int loadingResource) {
        ImageLoader.getInstance().displayImage(url, target, getOptions4PictureList(loadingResource));
    }

    /**
     * 当使用WebView加载大图的时候，使用本方法现下载到本地然后再加载
     *
     * @param url
     * @param loadingListener
     */
    public static void loadImageFromLocalCache(String url, SimpleImageLoadingListener loadingListener) {
        ImageLoader.getInstance().loadImage(url, getOption4ExactlyType(), loadingListener);
    }

    /**
     * 设置图片放缩类型为模式EXACTLY，用于图片详情页的缩放
     *
     * @return
     */
    public static DisplayImageOptions getOption4ExactlyType() {
        return new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .resetViewBeforeLoading(true)
                .considerExifParams(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .build();
    }

    /**
     * 加载头像专用Options，默认加载中、失败和空url为 ic_loading_small
     *
     * @return
     */
    public static DisplayImageOptions getOptions4Header() {
        return new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
//                .showImageForEmptyUri(R.drawable.ic_loading_small)
//                .showImageOnFail(R.drawable.ic_loading_small)
//                .showImageOnLoading(R.drawable.ic_loading_small)
                .build();
    }

    /**
     * 商品列表专用
     * @return
     */

    public static DisplayImageOptions getOptions4List() {
        return new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .showImageForEmptyUri(R.mipmap.bg)
                .showImageOnFail(R.mipmap.bg)
                .showImageOnLoading(R.mipmap.bg)
                .build();
    }

    /**
     * 加载图片列表专用，加载前会重置View
     * {@link com.nostra13.universalimageloader.core.DisplayImageOptions.Builder#resetViewBeforeLoading} = true
     *
     * @param loadingResource
     * @return
     */
    public static DisplayImageOptions getOptions4PictureList(int loadingResource) {
        return new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .resetViewBeforeLoading(true)
                .showImageOnLoading(loadingResource)
                .showImageForEmptyUri(loadingResource)
                .showImageOnFail(loadingResource)
                .build();
    }


    public static void clearMemoryCache() {
        getImageLoader().clearMemoryCache();
    }
    public static void loadImage(Activity activity,String url,ImageView imageView){
        loadImage(Glide.with(activity),url,imageView);
    }

    public static void loadImage(Context context,String url,ImageView imageView){
        loadImage(Glide.with(context),url,imageView);
    }

    public static void loadNewsHead(Activity activity,String url,ImageView imageView){
        Glide.with(activity).load(url).fitCenter().into(imageView);
    }

    public static void loadImage(Fragment fragment, String url, ImageView imageView){
        loadImage(Glide.with(fragment),url,imageView);
    }
    public static void loadImage(FragmentActivity fragment, String url, ImageView imageView){
        loadImage(Glide.with(fragment),url,imageView);
    }

    public static void loadImage(RequestManager manager,String url,ImageView imageView){
        if(!TextUtils.isEmpty(url)){
            manager.load(url).fitCenter().placeholder(R.mipmap.bg).error(R.mipmap.bg).into(imageView);
        }else {
            imageView.setImageResource(R.mipmap.bg);
        }
    }

    public static void clearMemory() {
        Glide.get(MyApp.mContext).clearMemory();
    }


}
